package cn.dnui_xqh414.dnuifood_16110100414.Fragment;


import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.dnui_xqh414.dnuifood_16110100414.R;
import cn.dnui_xqh414.dnuifood_16110100414.SQLite.RecordDBOperation;
import cn.dnui_xqh414.dnuifood_16110100414.SQLite.RecordSQLiteOpenHelper;
import cn.dnui_xqh414.dnuifood_16110100414.bean.ShopdetailBean;
import cn.dnui_xqh414.dnuifood_16110100414.fragment_adapter_and_vhoder.rv_Adapter;
import cn.dnui_xqh414.dnuifood_16110100414.fragment_adapter_and_vhoder.rv_Adapter_shopList;
import cn.dnui_xqh414.dnuifood_16110100414.listener.OnRetrofitListener;
import cn.dnui_xqh414.dnuifood_16110100414.model.UserModel;

/**
 * A simple {@link androidx.fragment.app.Fragment} subclass.
 */
public class SearchFragment
        extends androidx.fragment.app.Fragment
implements OnRetrofitListener<List<ShopdetailBean>> {

    private RecyclerView recyclerView;
    private EditText et_keyword;
    private ImageButton bt_search;
    private ChipGroup chipGroup;
    private TextView tv_history,tv_clear;

    private rv_Adapter_shopList adapter;

    private UserModel model = new UserModel();

    private RecordSQLiteOpenHelper helper;
    private RecordDBOperation recordDBO;

    public SearchFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_search, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        recyclerView = Objects.requireNonNull(getView()).findViewById(R.id.rv_search);
        et_keyword = view.findViewById(R.id.et_search);
        bt_search = view.findViewById(R.id.imgbt_search);
        chipGroup = view.findViewById(R.id.chipG_search);
        tv_history = view.findViewById(R.id.tv_history);
        tv_clear = view.findViewById(R.id.tv_historyClear);

        RecyclerView.LayoutManager layoutManager =
                new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        adapter = new rv_Adapter_shopList(getContext(),""); // TODO: 12/14/2018 phoneNum need complete
        recyclerView.setAdapter(adapter);

        helper = new RecordSQLiteOpenHelper(getContext());
        recordDBO = new RecordDBOperation(helper);

        bt_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!String.valueOf(et_keyword.getText()).equals("")) {
//                    ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
//                            getActivity().getCurrentFocus().getWindowToken(),
//                            InputMethodManager.HIDE_NOT_ALWAYS);
                    Log.e("****************", String.valueOf(et_keyword.getText()));

                    boolean hasData = recordDBO.hasData(String.valueOf(et_keyword.getText()));
                    if (!hasData) {
                        recordDBO.insertData(String.valueOf(et_keyword.getText()));
                        Chip chip = new Chip(Objects.requireNonNull(getContext()));
                        MyChipStyle(chip, String.valueOf(et_keyword.getText()));
                        chipGroup.addView(chip);
                    }
                    search(String.valueOf(et_keyword.getText())); //search
                } else {
                    Toast.makeText(getContext(), "please enter the keyword!", Toast.LENGTH_SHORT).show();
                }
            }
        });

        tv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chipGroup.removeAllViews();
                recordDBO.deleteData();
            }
        });

        List list = recordDBO.searchData();
        if (list.size() != 0){
            for (int i = 0; i < list.size(); i++) {
                final Chip chip = new Chip(Objects.requireNonNull(getContext()));
                chip.setText(String.valueOf(list.get(i)));
                MyChipStyle(chip,String.valueOf(list.get(i)));
                chipGroup.addView(chip);
            }
        }else {
            tv_history.setText("nope~~~");
        }

    }

    private void search(String key){
        if (!key.equals(""))
            model.getSearch(key,this);
    }

    @Override
    public void onSuccess(List<ShopdetailBean> object, int flag) {
        adapter.setList(null);
        if (object.size() != 0)
        adapter.setList(object);
        else
            Toast.makeText(getContext(), "nothing", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    //设置一哈统一的chip, 方便
    private void MyChipStyle(final Chip chip, final String text){
        chip.setText(text);
        chip.setChipBackgroundColorResource(R.color.colorAccent);
        chip.setClickable(true);
        chip.setCheckable(true);
        chip.setCloseIconVisible(true);
        chip.setCheckedIconVisible(false);
        chip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_keyword.setText(text);
                search(String.valueOf(chip.getText()));
            }
        });
        chip.setOnCloseIconClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recordDBO.deleteData_onebyone(String.valueOf(chip.getText()));
                chipGroup.removeView(chip);
            }
        });
    }
}
